package com.lu.nio.server;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.lu.nio.ChannelAdapter;
import com.lu.nio.ChannelHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.channels.Selector;
import java.util.Date;

/**
 * @program lu-netty
 * @description:
 * @author: zhanglu
 * @create: 2022-06-10 16:17:00
 */
@Slf4j
public class NioServerHandler extends ChannelAdapter {

    public NioServerHandler(Selector selector, String charset) {
        super(selector, charset);
    }

    @Override
    protected void channelActive() {
        try {
            log.info("{} 加入连接", this.ctx.channel().getLocalAddress());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void channelRead(Object msg) {
        String currentDate = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);
        log.info(StrUtil.format("{} --- 接收消息：{}", currentDate, msg));
        this.ctx.writeAndFlush(StrUtil.format("client-request:{} received", msg));
    }

}
